package com.xing.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import com.xing.db.DBService;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

public class Common {
	
	private static SQLiteDatabase db;
	
	/**
	 * download(by get)
	 * @param 
	 * @return
	 */
	public static String getUrl(String url,Context context) throws Exception{
		String result = null;
		
//	    if(isNetworkAvailable(context)){
//			url = url + "&imei="+Common.getIMEI(context);
		    String hostIp = SharedPreferenceUtil.getStringInfo(context,SharedPreferenceUtil.HOST_IP);
		    String port = SharedPreferenceUtil.getStringInfo(context, SharedPreferenceUtil.PORT);
			if (!(TextUtils.isEmpty(hostIp) && TextUtils.isEmpty(port))) {
				url = "http://"+hostIp + ":" + port+url;
			}else {
				url = AccessUrl.HOST_IP+url;
				
			}
			System.out.println(url);
			HttpGet httpGet = new HttpGet(url);
			HttpParams httpParameters = new BasicHttpParams();
			int timeoutConnection = 18000;
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			int timeoutSocket = 18000;
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
			DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			System.out.println("httpResponse.getStatusLine().getStatusCode()--"+httpResponse.getStatusLine().getStatusCode());
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				
				result = EntityUtils.toString(httpResponse.getEntity()); 
				System.out.println("result---"+result);
			}
//	    }
		return result;
	}
	
	/**
	 * post��ʽ�������
	 * @param key
	 * @param value
	 * @return
	 */
	 public static String downLoadByPost(Context context,String url,List<String> key,List<String> value) throws Exception
	     {
		 	String hostIp = SharedPreferenceUtil.getStringInfo(context,SharedPreferenceUtil.HOST_IP);
		    String port = SharedPreferenceUtil.getStringInfo(context, SharedPreferenceUtil.PORT);
			if (!(TextUtils.isEmpty(hostIp) && TextUtils.isEmpty(port))) {
				url = "http://"+hostIp + ":" + port+url;
			}else {
				url = AccessUrl.HOST_IP+url;
				
			}
			System.out.println(url);
	         String result = "";
	        
	         // HttpPostl�Ӷ���
	         HttpPost httpRequest = new HttpPost(url);
	         // ʹ��NameValuePair4����Ҫ���ݵ�Post����
	         List<NameValuePair> params = new ArrayList<NameValuePair>();
	         // ���Ҫ���ݵĲ���
	         for(int i = 0 ; i < key.size(); i++){
	        	 params.add(new BasicNameValuePair(key.get(i), value.get(i)));
	         }
	         // �����ַ�
	         HttpEntity httpentity = new UrlEncodedFormEntity(params, "Utf-8");
	         // ����httpRequest
	         httpRequest.setEntity(httpentity);
	         // ȡ��Ĭ�ϵ�HttpClient
	         HttpParams httpParameters = new BasicHttpParams();
			int timeoutConnection = 18000;
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			int timeoutSocket = 18000;
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
			DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
	         
	         
//	         DefaultHttpClient httpClient = new DefaultHttpClient();
	         // ȡ��HttpResponse
	         HttpResponse httpResponse = httpClient.execute(httpRequest);
	         // HttpStatus.SC_OK��ʾl�ӳɹ�
	         if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	             // ȡ�÷��ص��ַ�
	             result = EntityUtils.toString(httpResponse.getEntity());
	             System.out.println("result---"+result);
	             return result; 
	         } else {
	        	 System.out.println(httpResponse.getStatusLine().getStatusCode());
	              return "null";
	         }
	         
	         
	     }
	/**
	 * 下载图片
	 * @param url
	 * @param context
	 * @throws Exception
	 */
	public static void getBitMap(String url,Context context) throws Exception{
		HttpGet httpGet = new HttpGet(url);
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 80000;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		int timeoutSocket = 80000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream inputStream = httpEntity.getContent();
		
		String localSavePath = "/sdcard/xxx";
		File imageFile = new File(localSavePath);
		FileOutputStream outputStream = new FileOutputStream(imageFile);
		BufferedInputStream inputStreamBuffer = new BufferedInputStream(inputStream); 
	    byte[] buffer = new byte[1024];
		int bytes = 0;
		while ((bytes = inputStreamBuffer.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytes);
		}
		
		outputStream.flush();
		outputStream.close();
		
	}
	
	/**
	 * 
	 * 检测是否有可用网络
	 * 
	 * @param context
	 * @return 网络连接状态
	 */
	public static boolean isNetworkAvailable(Context context) {
		try {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			// 获取网络信息
			NetworkInfo info = cm.getActiveNetworkInfo();
			// 返回检测的网络状态
			return (info != null && info.isConnected());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}
	
//	public static synchronized SQLiteDatabase OpenDataBase(Context context) throws Exception{
//		DBService databaseOpenhelper=new DBService(context,DBService.dataBaseName, null, DBService.currentVersion);
//		db = databaseOpenhelper.getWritableDatabase();
//	    return db;
//	}
//	
//	
//	public static synchronized void closeDataBase() throws Exception{
//		if (db != null) {
//			db.close();
//		}
//	}
	

	
	
}
